﻿#include "GameNet.h"
#include <sys/types.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <iostream>
#include "MessageManager.h"
/*
#include "CCLuaEngine.h"
*/
#include "ODSocket.h"
#include "SocketThread.h"
#include "ODSocket.h"

std::string GameNet::ip = "";
int GameNet::port = 0;
int GameNet::fd = 0;
void* GameNet::buf = NULL;
GameNet::GameNet(string& ip, int port){
	buf = malloc(BUFF_SIZE);
	this->ip = ip;
	this->port = port;
}

GameNet::~GameNet(){
	free(buf);
}

bool GameNet::connect(string& ip, int port){
	SocketThread* socketThread = SocketThread::getInstance();
	if (socketThread->start(ip, port) != 0){
		return false;
	}
	return true;
}

//void* GameNet::read_thread(void* arg)
//{
//	log("start:%s\n", "recv");
//  while (true)
//  {
//    // len
//    int32 len = 0;
//	int status = ::recv(fd, (char *)buf, sizeof(len), 0);
//	log("status:%d\n", status);
//	
//	log("status:%d\n", status);
//    memcpy(&len, buf, sizeof(len));
//	log("len1:%d\n", len);
//    len = ntohl(len);
//	log("len2:%d\n", len);
//
//
//    // id + data
//	::recv(fd, (char *)buf, len, 0);
//    // id
//    int32 id;
//    memcpy(&id, buf, sizeof(id));
//	log("id1:%d\n", id);
//    id = ntohl(id);
//	log("id2:%d\n", id);
//    // data
//	recv_buf.writeDatas((char *)buf + sizeof(id), len - sizeof(id));
//
//    Message* msg = MessageManager::getMsg(id);
//    if (msg == NULL)
//    {
//		log("msg is null\n");
//      continue;
//    }
//    if (!msg->read_from(recv_buf))
//    {
//		log("read is wrong\n");
//      continue;
//    }
//	
//    recver->recv(*msg);
//    free(msg);
//	#ifdef WIN32
//		Sleep(1000);
//	#else
//		usleep(1000);
//	#endif
//   
//  }
//}
bool GameNet::init(){
	if (!connect(ip, port)){
		return false;
	}
	return true;
}

void GameNet::close(){
#ifdef WIN32
	closesocket(fd);
	WSACleanup();
#else
	shutdown(fd, SHUT_RDWR);
	::close(fd);
#endif
}
//
//int GameNet::send(Message& msg)
//{
//Message* msg1 = &msg;
//	return SocketThread::getInstance()->sendmessage(msg1);
//}


int GameNet::conn(string& ip, int port){
	log("GameNet conn");
	MessageManager::init();
	SocketThread::getInstance()->SendCount = 0;
	//GameMsgRecver* recver = new Recver();
	//log("%s \n", "create GameNet()！");
	if (instance == NULL)
		instance = new GameNet(ip, port);
	if (instance->init()){
		return 0;
	}
	else{
		return 1;
	}
}

bool GameNet::reconn(string& ip, int port){
	log("GameNet reconn");
	SocketThread* socketThread = SocketThread::getInstance();
	socketThread->SendCount = 0;
	socketThread->ip = ip;
	socketThread->port = port;
	ODSocket csocket = socketThread->getSocket();
	if (csocket){
		csocket.Close();
		//delete csocket;		
	}
	ODSocket cdSocket;
	cdSocket.Init();
	bool isok = cdSocket.Create(AF_INET, SOCK_STREAM, 0);
	if (isok) {
	}
	bool iscon = cdSocket.Connect(ip.c_str(), port);

	csocket = cdSocket;
	socketThread->csocket = cdSocket;
	return iscon;
}

GameNet* GameNet::instance = NULL;
